<?php

namespace Service\Http\Controller;

use Service\AjaxModel\AjaxResponse;
use Service\Http\Exception\RestException;
use Service\Http\Request;
use Service\Model\Order;

class OrderController extends Controller
{
    /**
     * @throws RestException
     */
    public function list(Request $request): AjaxResponse
    {
        $user = $this->getUserObj($request);
        $order = new Order();
        if ($this->checkUserAdminRole($user)) {
            $result = $order->select([[1, '=', 1]], false);
        } else {
            $result = $order->select([['user_id', '=', $user['id']]], false);
        }
        return AjaxResponse::success($result->fetch_all(MYSQLI_ASSOC));
    }

    /**
     * @throws RestException
     */
    public function create(Request $request): AjaxResponse
    {
        $user = $this->getUserObj($request);
        $order = new Order();
        $order->id = md5(rand());
        $order->user_id = $user['id'];
        $order->order_item = $request->payload['item_id'];
        return AjaxResponse::success(['success' => $order->insert()]);
    }

    /**
     * @throws RestException
     */
    public function delete(Request $request): AjaxResponse
    {
        $user = $this->getUserObj($request);
        if (!$this->checkUserAdminRole($user)) {
            throw new RestException('当前用户无权删除', 403);
        }
        $order = new Order();
        $order->id = $request->payload['id'];
        return AjaxResponse::success(['success' => $order->delete()]);
    }
}
